package com.beagle.njddapp.utils;

import android.app.Activity;
import android.os.Handler;
import android.os.Message;

import androidx.annotation.NonNull;

import com.alipay.sdk.app.PayTask;
import com.beagle.njddapp.base.ApiService;
import com.beagle.njddapp.base.RetrofitHttp;
import com.beagle.njddapp.bean.WxPayBean;
import com.beagle.njddapp.bean.ZkBean;
import com.beagle.njddapp.event.PayEvent;
import com.beagle.njddapp.event.PayResultEvent;
import com.beagle.njddapp.net.BaseOilHttpResponse;
import com.beagle.njddapp.net.HttpResponseObserver;
import com.beagle.njddapp.net.RxSchedulers;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

import static com.blankj.utilcode.util.SnackbarUtils.getView;

/**
 * @author hxx
 * @date 2021-06-30 11:51
 */
public class PayControler {

    private Activity context;
    private AtomicInteger atomicInteger;
    private Handler mHandler=new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            if (msg.what==1000||msg.what==1001){
                search();
            }
            super.handleMessage(msg);
        }
    };
    public static final String APP_ID = "wx3d87e26691a0338a";
    public IWXAPI msgApi;
    private PayReq req;
    private String orderId;
    public PayControler(Activity context) {
        this.context = context;
        EventBus.getDefault().register(this);
        msgApi = WXAPIFactory.createWXAPI(context,APP_ID,false);
        atomicInteger=new AtomicInteger(0);
    }

    public void aLipay(String info,String orderId_out){
        orderId=orderId_out;
        Runnable runnable=new Runnable() {
            @Override
            public void run() {
                PayTask alipay = new PayTask(context);
                Map<String,String> result = alipay.payV2(info,true);
                Message msg = new Message();
                msg.what = 1000;
                msg.obj = result;
                mHandler.sendMessageDelayed(msg,1000);
            }
        };
        new Thread(runnable).start();
    }
    public void wxPay(WxPayBean bean,String orderId_out){
        orderId=orderId_out;
        Runnable runnable=new Runnable() {
            @Override
            public void run() {
                req = new PayReq();
                if (null != bean.getResult()) {
                    req.appId = bean.getResult().getAppid();
                    req.partnerId = bean.getResult().getPartnerid();
                    req.prepayId = bean.getResult().getPrepay_id();
                    req.packageValue = "Sign=WXPay";
                    req.nonceStr = bean.getResult().getNoncestr();
                    req.timeStamp = bean.getResult().getTimestamp()+"";
                    req.sign = bean.getResult().getSign();
                    msgApi.sendReq(req);
                }
//                Message msg = new Message();
//                msg.what = 1001;
//                mHandler.sendMessage(msg);
            }
        };
        new Thread(runnable).start();;
    }
    @Subscribe ()
    public void onPay(PayEvent pay){
        mHandler.sendEmptyMessageDelayed(1001,1000);
    }


    public void search(){
        if (atomicInteger.get()==3){
            ToastUtils.showShort("支付失败");
            EventBus.getDefault().post(new PayResultEvent(false));
            return;
        }
        retrofit2.Retrofit retrofit = RetrofitHttp.provideRetrofit();
        ApiService apiService = retrofit.create(ApiService.class);
        apiService.paymentInfo(orderId).compose(RxSchedulers.compose()).safeSubscribe(new HttpResponseObserver<BaseOilHttpResponse<ZkBean>>() {
            @Override
            public void success(BaseOilHttpResponse<ZkBean> oilHttpResponse) {
                atomicInteger.incrementAndGet();
                LogUtils.d("success");
                if (oilHttpResponse!=null&&oilHttpResponse.result!=null){
                    if (oilHttpResponse.result.isPayResult()){
                        ToastUtils.showShort("支付成功");
                        EventBus.getDefault().post(new PayResultEvent(true));
                    }else {
                        mHandler.sendEmptyMessageDelayed(1001,1500);
                    }
                }else {
                    mHandler.sendEmptyMessageDelayed(1001,1500);
                }
            }

            @Override
            public void error(int code, String message) {
                mHandler.sendEmptyMessageDelayed(1001,1500);
            }
        });
    }
    public void clear(){
        EventBus.getDefault().unregister(this);
    }

}
